<template>
  <div class="createPost-container">
    <el-form v-if="!infoLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <el-form-item label="栏目">
              <el-radio-group v-model="postForm.businessTable" @change="changeTable">
                <el-radio-button label="bus_dynamic_center" border>要闻速递</el-radio-button>
                <el-radio-button label="bus_data_center" border>专题课程</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <dynamicList v-if="postForm.businessTable==='bus_dynamic_center'" :is-edit="false" :is-selection="true" @selected="selected" />
        <dataCenterList v-if="postForm.businessTable==='bus_data_center'" :is-edit="false" :is-selection="true" @selected="selected" />
        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.title" :maxlength="100" name="name" required>
                标题
              </MDinput>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="封面图片" style="clear:both">
          <el-upload
            class="avatar-uploader"
            :action="this.$http.defaults.baseURL+'api/gen/file/upload/'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="myHeaders"
            accept="image/jpeg,image/png,image/gif"
          >
            <img v-if="imageUrl" :src="this.$http.defaults.baseURL+'api/gen/file/download?id='+parseInt(imageUrl)" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item style="margin-bottom: 30px;">
          <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
        </el-form-item>

      </div>
    </el-form>
  </div>
</template>

<script>
import MDinput from '@/components/MDinput'
import dynamicList from '@/views/dynamic/list.vue'
import dataCenterList from '@/views/datacenter/list.vue'
const defaultForm = {
  businessId: null,
  businessTable: 'bus_dynamic_center',
  coverImg: null, // 文章内容
  id: null,
  state: 1,
  title: '' // 文章题目
}
export default {
  name: 'ArticleDetail',
  components: { MDinput, dynamicList, dataCenterList },
  props: {
    infoid: {
      type: Number,
      default: 0
    },
    timestamp: {
      type: Number,
      default: 0
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: '请将表单填写完整',
          type: 'error'
        })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      classOption: [],
      rules: {
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }]
      },
      tempRoute: {},
      selectedId: 0,
      infoType: 0
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        console.log('val:' + val)
        this.getData(this.infoid)
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
  },
  created() {
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    changeTable() {
      this.selectedId = null
    },
    selected(data) {
      this.selectedId = data.id
      this.postForm.title = data.title
      this.imageUrl = data.coverImg
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.imageUrl = res.result[0].id
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!')
        return false
      }
    },
    getData(id) {
      if (id) {
        this.infoLoading = true
        this.$http
          .get('/api/busTopic/getDetailById?&id=' + id)
          .then(response => {
            this.infoLoading = false
            if (response.data.success === true) {
              console.log(response.data)
              this.postForm = response.data.result
              this.selectedId = response.data.result.businessId
              this.imageUrl = response.data.result.coverImg
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
          })
      } else {
        this.postForm = Object.assign({}, defaultForm)
        this.imageUrl = ''
      }
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          if (this.selectedId) {
            const day = new Date()
            day.setTime(day.getTime())
            const para = {
              businessId: this.selectedId,
              businessTable: this.postForm.businessTable,
              coverImg: this.imageUrl,
              id: this.postForm.id ? this.postForm.id : null,
              publishTime: day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate()),
              state: this.postForm.state,
              title: this.postForm.title
            }
            this.loading = true
            this.$http
              .post('/api/busTopic/save', para)
              .then(response => {
                this.loading = false
                if (response.data.success === true) {
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  })
                  this.$emit('dialogHide')
                } else {
                  console.log('提交失败:' + response.data.message)
                  this.$message({
                    message: '提交失败:' + response.data.message,
                    type: 'error'
                  })
                }
              })
              .catch(function(error) {
                console.log(error)
                this.loading = false
              })
            this.postForm.status = 'published'
            this.postForm = Object.assign({}, defaultForm)
            this.loading = false
          } else {
            this.$message({
              message: '请选取一条信息',
              type: 'error'
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    // padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
